package vd.cloud.com.services;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import vd.cloud.com.dao.SchoolDAO;
import vd.cloud.com.dao.SchoolTypeDAO;
import vd.cloud.com.entities.SchoolEntity;
import vd.cloud.com.entities.SchoolTypeEntity;

import java.util.List;

/**
 * Created by VIET on 2/18/2015.
 */
@Service
@RequestMapping("/school")
public class SchoolService {

    private static final Logger logger = Logger.getLogger(SchoolService.class);

    @Autowired
    private SchoolDAO schoolDAO;

    @Autowired
    private SchoolTypeDAO schoolTypeDAO;

    @RequestMapping("/findAll")
    @ResponseBody
    public List<SchoolEntity> findAll(){
        List<SchoolEntity> schoolEntities =  schoolDAO.findAll();
        if(logger.isDebugEnabled()){
            logger.debug("/findAll schools: " + schoolEntities.size());
        }
        return schoolEntities;
    }

    @RequestMapping("/{name}")
    @ResponseBody
    public List<SchoolEntity> findByName(@PathVariable(value = "name") String name){
        List<SchoolEntity> schoolEntities =  schoolDAO.findByNameLike(name);
        if(logger.isDebugEnabled()){
            logger.debug("/findByName schools: " + schoolEntities.size());
        }
        return schoolEntities;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public SchoolEntity addSchool(@RequestParam(value = "name",required = true) String name,
                                  @RequestParam(value = "type",required = true) String type){
        SchoolEntity schoolEntity = new SchoolEntity();
        schoolEntity.setName(name);
        schoolEntity.setType(new SchoolTypeEntity(type));
        if(logger.isDebugEnabled()){
            logger.debug("/add: " + schoolEntity.getName());
        }
        return schoolDAO.insert(schoolEntity);
    }

    @RequestMapping("/type/findAll")
    @ResponseBody
    public List<SchoolTypeEntity> findAllType(){
        List<SchoolTypeEntity> typeEntities = schoolTypeDAO.findAll();
        if(logger.isDebugEnabled()){
            logger.debug("/findAllType: ");
        }
        return typeEntities;
    }
}
